package com.rt.tmpt.service.impl;

import com.rt.tmpt.bean.*;
import com.rt.tmpt.dao.intf.IA2UserDao;
import com.rt.tmpt.dao.intf.IA3MenuDao;
import com.rt.tmpt.enums.DataLimitType;
import org.json.JSONArray;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by wxy on 2017/10/14.
 */
@Service(value="dataLimitService")
@Transactional(propagation= Propagation.REQUIRED)
public class DataLimitService {

    @Resource private IA2UserDao a2UserDao;
    @Resource private IA3MenuDao a3MenuDao;

    /**
     * 通过传入的参数取数据分界需要的数据
     * @param paramMap
     * @return
     */
    public  Map<String,Object> getLimitParam(Map<String,Object> paramMap){
        if(paramMap == null){
            return null;
        }
        Map<String,Object> paramMapReturn = new HashMap<>();
        paramMapReturn.putAll(paramMap);//其它方面的查询条件也在里面
        Object userIdObj = paramMap.get("userId");
        if(userIdObj == null){
            return paramMapReturn;
        }

        long userId = Long.valueOf(userIdObj.toString());
        System.out.println("====>userId:"+userId);

        Optional<A2User> optionalA2user = a2UserDao.findById(userId);
        A2User a2User = optionalA2user.get();
        A2Dept a2Dept = a2User.getA2Dept();
        A2Company a2Company = a2Dept.getA2Company();
        long companyId = a2Company.getId();
        System.out.println("====>companyId:"+companyId);
        String contextPath = (String)paramMap.get("contextPath");
        String requireUrl = (String)paramMap.get("requireUrl");
        String queryString = (String)paramMap.get("queryString");
        //long menu2Id = Long.valueOf(paramMap.get("menu2Id") == null ? "0" : paramMap.get("menu2Id").toString());
        long menuId = getMenuIdByUrl(contextPath,requireUrl,queryString);
        System.out.println("====>menuId:"+menuId);

        //取当前用户访问的二级菜单的最高权限数据边界值
        int dataLimitType = getDataLimitType(userId,menuId);

        paramMapReturn.put("dataLimitType",dataLimitType);
        paramMapReturn.put("userId",userId);
        paramMapReturn.put("companyId",companyId);
        //enum 给Mybatis.xml使用
        paramMapReturn.put("OnlyMySelf", DataLimitType.OnlyMySelf.getKeyName());
        paramMapReturn.put("LowPost", DataLimitType.LowPost.getKeyName());
        paramMapReturn.put("SamePostAndLowPost", DataLimitType.SamePostAndLowPost.getKeyName());
        paramMapReturn.put("LowCompany", DataLimitType.LowCompany.getKeyName());
        paramMapReturn.put("All", DataLimitType.All.getKeyName());


        return paramMapReturn;
    }

    /**
     * 通过url地址找menu2Id
     // requireUrl : /zpmng//admin123/template/templateAjax_queryListBySearch
     // requireUrlFunction : /admin123/template/templateAjax_queryListBySearch
     * @param contextPath
     * @param requireUrl
     * @return
     */
    private  long getMenuIdByUrl(String contextPath, String requireUrl, String queryString){
        if(queryString!=null) {
            requireUrl = requireUrl + "?" + queryString;
        }
        System.out.println("====>contextPath:" + contextPath);
        System.out.println("====>requireUrl:" + requireUrl);

        List<String> urlList = new ArrayList<>();
        urlList.add(requireUrl);
        urlList.add(requireUrl.replaceFirst(contextPath+"/",""));
        urlList.add(requireUrl.replaceFirst(contextPath, ""));

        for(String url:urlList) {
            /*Search search = new Search();
            search.clear();
            search.addFilterEqual("url", url);
            search.addFilterEqual("deleteFlag", "0");*/
            A3Menu a3Menu = new A3Menu();
            a3Menu.setUrl(url);
            a3Menu.setDeleteFlag(0);
            List<A3Menu> menuList = a3MenuDao.findAll(Example.of(a3Menu));


            if (menuList.size() > 0) {
                A3Menu menu = menuList.get(0);
                long type = menu.getType();
                if(type == 20){
                    return menu.getId();
                }else if(type == 30){
                    return menu.getA3MenuParent().getId();
                }
            }
        }

        return 0;
    }


    /**
     * 取当前用户访问的菜单的最高权限数据边界值
     * type:0=menu; 10=leave menu; 20=function 30=function url
     * @param userId
     * @param menuId type must be 20=function, role-menu link table 中存储的type是20=function
     * @return
     */
    private  int getDataLimitType(long userId, long menuId) {
        //int dataLimitType = Integer.parseInt(DataLimitType.OnlyMySelf.getKeyName());
        int dataLimitType = Integer.parseInt(DataLimitType.All.getKeyName());
        Optional<A3Menu> optionalA3Menu = a3MenuDao.findById(menuId);
        if(!optionalA3Menu.isPresent())return dataLimitType;
        A3Menu menu = optionalA3Menu.get();
        //菜单是否要访问边界控制（1：要，0：不要）
        int hasDataLimit = menu.getHasDataLimit();
        //这个菜单不做边界控制
        if(hasDataLimit==0){
            dataLimitType =  Integer.parseInt(DataLimitType.All.getKeyName());
            return dataLimitType;
        }

        List<A3Menu> menuList = new ArrayList<A3Menu>();
        JSONArray jsonArr = new JSONArray();
        A2User user = a2UserDao.findById(userId).get();
        //取用户所有角色
        List<A2Role> roleList = user.getA2RoleList();
        for(A2Role role : roleList){
            List<A3MenuMy> menuMyList = role.getA3MenuMyList();
            for(A3MenuMy menuMy : menuMyList){
                if(menuMy.getA3Menu().getId()!=menuId)continue;
                //compare right
                int dataLimitTypeTmp = menuMy.getDataLimitType();
                if(DataLimitType.isHighThan(dataLimitTypeTmp,dataLimitType)){
                    dataLimitType = dataLimitTypeTmp;
                }
            }
        }
        return dataLimitType;
    }


}
